package com.mangguo.tingjian.user.controller;


import com.mangguo.tingjian.common.Result;
import com.mangguo.tingjian.user.dto.CountResult;
import com.mangguo.tingjian.user.service.IDwUserLiveAppService;
import com.mangguo.tingjian.util.CvsUtils;
import com.mangguo.tingjian.util.DateUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * app活跃用户表 前端控制器
 * </p>
 *
 * @author auto
 * @since 2019-11-23
 */
@RestController
@RequestMapping("/user/dw-user-live-app")
@AllArgsConstructor
@Slf4j
public class DwUserLiveAppController {

    private final IDwUserLiveAppService dwUserLiveAppService;

    /**
     * 当月MAU(活跃用户数)
     * @return
     */
    @GetMapping("/unique-imei/mau")
    public Result<Long> userNumMau(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
        Integer start = Integer.valueOf(simpleDateFormat.format(new Date())) * 100;
        return Result.success(dwUserLiveAppService.countUniqueImeiBetweenDate(start + 1, start + 31));
    }

    /**
     * 今日(活跃用户数)
     * @return
     */
    @GetMapping("/unique-imei/today")
    public Result<Long> userNumToday(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Integer start = Integer.valueOf(simpleDateFormat.format(new Date()));
        return Result.success(dwUserLiveAppService.countUniqueImeiBetweenDate(start, start));
    }

    /**
     * 活跃用户数按月份统计(12个月)
     * @return
     */
    @GetMapping("/unique-imei/month")
    public Result<List<CountResult>> userCountByMonth(){
        Integer end = DateUtils.getTodayInt();
        Integer start = DateUtils.addDay(end, -400);
        Map<String, CountResult> map = new HashMap<>();
        Integer year = DateUtils.getTodayYear();
        Integer month = DateUtils.getTodayMonth();
        for (int i = 0; i < 12; i++) {
            CountResult countResult = new CountResult();
            countResult.setMYear(year);
            countResult.setMMonth(month);
            countResult.setCount(0L);
            map.put(year.toString() + month.toString(), countResult);
            month--;
            if(month.equals(0)){
                month = 12;
                year--;
            }
        }



        dwUserLiveAppService.countUniqueImeiByMonth(start, end).forEach(countResult -> {
            if(map.get(countResult.getMYear().toString() + countResult.getMMonth().toString()) != null){
                map.get(countResult.getMYear().toString() + countResult.getMMonth().toString()).setCount(countResult.getCount());
            }
        });

        List<CountResult> results = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            month++;
            if(month.equals(13)){
                month = 1;
                year++;
            }
            results.add(map.get(year.toString() + month.toString()));
        }


        return Result.success(results);
    }

    /**
     * 活跃用户数按周统计(8周)
     * @return
     */
    @GetMapping("/unique-imei/week")
    public Result<List<CountResult>> userCountByWeek(){
        //前推8周
        Integer end = DateUtils.getTodayInt();
        Integer start = DateUtils.addDay(end, -80);
        Map<String, CountResult> map = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Integer dateTemp = end;
        for(;;){
            try {
                Date date = simpleDateFormat.parse(dateTemp.toString());
                CountResult countResult = new CountResult();
                countResult.setMMonth(DateUtils.getMonthInt(date));
                countResult.setMWeek(DateUtils.getWeekInt(date));
                countResult.setMYear(DateUtils.getYearInt(date));
                countResult.setCount(0L);
                map.put(DateUtils.getYearInt(date) + "-" + DateUtils.getMonthInt(date) + "-" + DateUtils.getWeekInt(date), countResult);
                if(map.size() == 8){
                    break;
                }
                dateTemp = DateUtils.addDay(dateTemp, -1);
            } catch (ParseException e) {
                log.error("日期解析异常",e);
                break;
            }
        }
        dwUserLiveAppService.countUniqueImeiByWeek(start, end).forEach(countResult -> {
            if(map.get(countResult.getMYear()+ "-" + countResult.getMMonth()+ "-" + countResult.getMWeek()) != null){
                map.get(countResult.getMYear()+ "-" + countResult.getMMonth()+ "-" + countResult.getMWeek()).setCount(countResult.getCount());
            }
        });

        List<CountResult> results = new ArrayList<>();
        dateTemp = end;
        Set<String> set = new TreeSet<>();
        for (;;) {
            try {
                Date date = simpleDateFormat.parse(dateTemp.toString());
                String key = DateUtils.getYearInt(date) + "-" + DateUtils.getMonthInt(date) + "-" + DateUtils.getWeekInt(date);
                CountResult countResult = map.get(key);
                if (!set.contains(key)){
                    set.add(key);
                    results.add(countResult);
                }
                if(set.size() == 8){
                    break;
                }
                dateTemp = DateUtils.addDay(dateTemp, -1);
            } catch (ParseException e) {
                log.error("日期解析异常",e);
                break;
            }
        }
        Collections.reverse(results);
        return Result.success(results);
    }

    /**
     * 活跃用户数按日统计（30天）
     * @return
     */
    @GetMapping("/unique-imei/date")
    public Result<List<CountResult>> userCountByDate(){
        Integer end = DateUtils.getTodayInt();
        Integer start = DateUtils.addDay(end, -30);
        Map<Integer, CountResult> map = new HashMap<>();
        DateUtils.getBetweenDates(start, end).forEach(date -> {
            CountResult countResult = new CountResult();
            countResult.setMDate(date);
            countResult.setCount(0L);
            map.put(date, countResult);
        });
        dwUserLiveAppService.countUniqueImeiByDate(start, end).forEach(countResult -> {
            map.get(countResult.getMDate()).setCount(countResult.getCount());
        });
        List<CountResult> results = new ArrayList<>();
        DateUtils.getBetweenDates(start, end).forEach(date -> {
            results.add(map.get(date));
        });
        return Result.success(results);
     }


    /**
     * 活跃用户数按月份统计
     * @return
     */
    @GetMapping("/unique-imei/month/download")
    public void userCountByMonthDownload(HttpServletResponse response){
        List<CountResult> countResults = dwUserLiveAppService.countUniqueImeiByMonth();
        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList("日期", "人数"));
        for(CountResult countResult : countResults){
            list.add(Arrays.asList(countResult.getMYear() + "-" + countResult.getMMonth(), countResult.getCount().toString()));
        }
        CvsUtils.downloadCvs(response, "APP月活统计", list);
    }

    /**
     * 活跃用户数按周统计
     * @return
     */
    @GetMapping("/unique-imei/week/download")
    public void userCountByWeekDownload(HttpServletResponse response){
        List<CountResult> countResults = dwUserLiveAppService.countUniqueImeiByWeek();
        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList("日期", "人数"));
        for(CountResult countResult : countResults){
            list.add(Arrays.asList(countResult.getMYear() + "年" + countResult.getMMonth() + "月" + countResult.getMMonth() + "周", countResult.getCount().toString()));
        }
        CvsUtils.downloadCvs(response, "APP周活统计", list);
    }

    /**
     * 活跃用户数按日统计
     * @return
     */
    @GetMapping("/unique-imei/date/download")
    public void userCountByDateDownload(HttpServletResponse response){
        List<CountResult> countResults = dwUserLiveAppService.countUniqueImeiByDate();
        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList("日期", "人数"));
        for(CountResult countResult : countResults){
            list.add(Arrays.asList(countResult.getMDate().toString(), countResult.getCount().toString()));
        }
        CvsUtils.downloadCvs(response, "APP日活统计", list);
    }

}
